﻿Public Class frmMain
    Public strCurrentVersion = "1"
    Public HighlightChecker As New Highlighting

    Public Enum State
        Idle = 0
        OpeningFile = 1
        ApplyHighlight = 2
        FindReplace = 3
    End Enum

    Public ProgramState As State = State.Idle

    ' Currently open project files
    Public OpenProjects As New SortedList

    ' Show a messagebox for the exception
    Public Sub HandleException(ByVal e As Exception)
        MsgBox(e.ToString())
    End Sub

    ' Extract the filename.ext from a full filepath
    Public Function ExtractFilename(ByVal strFilepath As String) As String
        Try
            Dim i As Integer = strFilepath.LastIndexOf("\")

            If (i <> -1) Then
                Return strFilepath.Substring(i + 1)
            End If

            Return ""

        Catch ex As Exception
            HandleException(ex)

            Return ""
        End Try
    End Function

    Public Function CleanSTR(ByVal strInput As String) As String
        Try
            Dim strTemp As String = strInput
            Dim charTemp As Char = ""

            Dim reader As New IO.StringReader(strTemp)

            While True
                charTemp = ChrW(reader.Peek())

                If charTemp = vbTab Or charTemp = " " Then
                    reader.Read()
                    Continue While

                Else
                    Return reader.ReadToEnd()
                End If
            End While

            Return 0

        Catch ex As Exception
            HandleException(ex)
            Return ""
        End Try
    End Function

    Public Sub EditAreaChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Try
            If (ProgramState <> State.Idle) Then Return

            If (tcMain.TabPages.Count = 0) Then Return
            If (OpenProjects.ContainsKey(tcMain.SelectedTab.Text) = False) Then Return

            Dim txtEditArea As RichTextBox = CType(sender, RichTextBox)

            If (txtEditArea.Parent.Name = tcMain.SelectedTab.Name) Then
                lblLines.Text = "Lines: " + txtEditArea.Lines.Count.ToString()

                CType(OpenProjects(tcMain.SelectedTab.Text), Project).UpdateEvents()

                UpdateEventList(tcMain.SelectedTab.Text)
                UpdateTodoList(tcMain.SelectedTab.Text)

                Dim Chars(2) As Char

                Chars(0) = vbLf
                Chars(1) = " "
                Chars(2) = vbTab

                Dim iWordBegin As Integer = txtEditArea.Text.Substring(0, txtEditArea.SelectionStart).LastIndexOfAny(Chars)
                Dim strCurrentWord As String = ""

                If (iWordBegin = -1) Then
                    iWordBegin = 0
                Else
                    iWordBegin += 1
                End If

                Dim iWordLength As Integer = txtEditArea.SelectionStart - iWordBegin

                strCurrentWord = txtEditArea.Text.Substring(iWordBegin, iWordLength)

                If (strCurrentWord.StartsWith("+") = True Or strCurrentWord.StartsWith("-") = True) Then
                    strCurrentWord = strCurrentWord.Substring(1)

                    iWordBegin += 1

                    iWordLength -= 1
                End If

                lstEventList.BeginUpdate()
                lstEventList.Focus()

                HighlightChecker.ApplyToWord(strCurrentWord, txtEditArea, iWordBegin, strCurrentWord.Length, True)

                txtEditArea.SelectionStart += iWordLength
                txtEditArea.SelectionLength = 0

                txtEditArea.SelectionColor = HighlightChecker.EditorColour
                txtEditArea.SelectionFont = HighlightChecker.EditorFont
                txtEditArea.Focus()
                lstEventList.EndUpdate()
            End If

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Public Sub EditAreaSelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Try
            If (tcMain.TabPages.Count = 0) Then Return

            Dim txtEditArea As RichTextBox = CType(sender, RichTextBox)

            If (txtEditArea.Parent.Name = tcMain.SelectedTab.Name) Then
                lblColumn.Text = "Character: " + txtEditArea.SelectionStart.ToString()

                Dim iLine As Integer = txtEditArea.GetLineFromCharIndex(txtEditArea.SelectionStart) + 1

                lblLine.Text = "Line: " + iLine.ToString()
            End If

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Public Sub EditAreaKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        Try
            If (tcMain.TabPages.Count = 0) Then Return

            Dim txtEditArea As RichTextBox = CType(sender, RichTextBox)

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Public Sub UpdateEventList(ByVal strProject As String)
        Try
            If (OpenProjects.ContainsKey(strProject) = False) Then Return
            If (tcMain.TabPages.Count = 0) Then Return

            lstEventList.Items.Clear()

            lstEventList.BeginUpdate()

            For Each f As EventInfo In CType(OpenProjects(strProject), Project).EventList
                lstEventList.Items.Add(f.iLine.ToString() + ":" + vbTab + f.strName)
            Next

            lstEventList.EndUpdate()
        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Public Sub UpdateTodoList(ByVal strProject As String)
        Try
            If (OpenProjects.ContainsKey(strProject) = False) Then Return
            If (tcMain.TabPages.Count = 0) Then Return

            lstTodoList.Items.Clear()

            lstTodoList.BeginUpdate()

            For Each t As TodoInfo In CType(OpenProjects(strProject), Project).TodoList
                lstTodoList.Items.Add(t.iLine.ToString() + ":" + vbTab + t.strInfo)
            Next

            lstTodoList.EndUpdate()
        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            Me.Text = "NBDev v" + My.Application.Info.Version.ToString() + " http://www.pkmnonline.org © Pandepic"

            ' Setup Open File Dialogue
            dlgOpenFile.DefaultExt = "nbd"
            dlgOpenFile.AddExtension = True
            dlgOpenFile.Filter = "NBDev Files (*.nbd)|*.nbd"
            dlgOpenFile.Title = "Open NBDev Project"
            dlgOpenFile.Multiselect = True

            ' Setup Save File Dialogue
            dlgSaveFile.DefaultExt = "nbd"
            dlgSaveFile.AddExtension = True
            dlgSaveFile.Filter = "NBDev Files (*.nbd)|*.nbd"
            dlgOpenFile.Title = "Save NBDev Project"

            Dim args() As String = Environment.GetCommandLineArgs

            If (args.Length > 1) Then
                OpenProject(args(1))
            End If

            lblLine.Text = ""
            lblColumn.Text = ""

            SyntaxCheck.InitialiseSyntax()

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub tsmExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmExit.Click
        Try
            End

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub tsmOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmOpen.Click
        Try
            Dim strName As String = ""

            Dim bSetLines As Boolean = True

            If (dlgOpenFile.ShowDialog() = Windows.Forms.DialogResult.OK) Then
                For Each strFilepath As String In dlgOpenFile.FileNames
                    OpenProject(strFilepath)
                Next
            End If

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub tsmSaveAs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmSaveAs.Click
        Try
            If (tcMain.TabPages.Count = 0) Then Return
            If (OpenProjects.ContainsKey(tcMain.SelectedTab.Text) = False) Then Return

            If (dlgSaveFile.ShowDialog() = Windows.Forms.DialogResult.OK) Then
                CType(OpenProjects(tcMain.SelectedTab.Text), Project).Save(dlgSaveFile.FileName)
            End If

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub tsmSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmSave.Click
        Try
            If (tcMain.TabPages.Count = 0) Then Return
            If (OpenProjects.ContainsKey(tcMain.SelectedTab.Text) = False) Then Return

            CType(OpenProjects(tcMain.SelectedTab.Text), Project).Save(CType(OpenProjects(tcMain.SelectedTab.Text), Project).strFilepath)

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub tsmPublish_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmPublish.Click
        Try
            If (tcMain.TabPages.Count = 0) Then Return

            PublishProject(tcMain.SelectedTab.Text)
        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub tcMain_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tcMain.SelectedIndexChanged
        Try
            If (tcMain.TabPages.Count = 0) Then Return

            Dim tpTemp As TabPage = tcMain.SelectedTab
            Dim txtEditArea As RichTextBox = tpTemp.Controls.Item(0)

            lblLines.Text = "Lines: " + txtEditArea.Lines.Count.ToString()
            lblColumn.Text = "Character: " + txtEditArea.SelectionStart.ToString()

            Dim iLine As Integer = txtEditArea.GetLineFromCharIndex(txtEditArea.SelectionStart) + 1

            lblLine.Text = "Line: " + iLine.ToString()

            UpdateEventList(tcMain.SelectedTab.Text)
            UpdateTodoList(tcMain.SelectedTab.Text)

            txtEditArea.Focus()

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub tsmClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmClose.Click
        Try
            If (tcMain.TabPages.Count = 0) Then Return

            OpenProjects.Remove(tcMain.SelectedTab.Text)

            tcMain.TabPages.RemoveByKey(tcMain.SelectedTab.Name)

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub tsmNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmNew.Click
        Try
            If (dlgSaveFile.ShowDialog() = Windows.Forms.DialogResult.OK) Then
                Dim strFilepath As String = dlgSaveFile.FileName
                Dim strName As String = ExtractFilename(strFilepath)

                If (OpenProjects.ContainsKey(strName) = True) Then
                    OpenProjects.Remove(strName)
                    tcMain.TabPages.RemoveByKey("tp" + strName)
                End If

                Dim Stream As New IO.FileStream(strFilepath, IO.FileMode.Create)

                Stream.Close()

                OpenProject(strFilepath)
            End If

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub lstEventList_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lstEventList.MouseDoubleClick
        Try
            If (lstEventList.Items.Count = 0) Then Return
            If (tcMain.TabPages.Count = 0) Then Return

            Dim iLine As Integer = CType(lstEventList.SelectedItem.ToString().Substring(0, lstEventList.SelectedItem.ToString().IndexOf(":")), Integer)

            If (IsNumeric(iLine) = False) Then Return

            Dim txtEditArea As RichTextBox = tcMain.SelectedTab.Controls("txtEditArea")

            Dim i As Integer = 0
            Dim n As Integer = 0
            Dim bFinished As Boolean = False

            For Each c As Char In txtEditArea.Text
                If (c = vbNewLine Or c = vbLf Or c = vbCr Or c = vbCrLf) Then
                    n += 1

                    If (n = iLine) Then
                        Exit For
                    End If
                End If

                i += 1
            Next

            txtEditArea.Select(i, 1)

            txtEditArea.ScrollToCaret()
            
        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub lstErrors_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lstErrors.MouseDoubleClick
        Try
            If (lstErrors.Items.Count = 0) Then Return
            If (tcMain.TabPages.Count = 0) Then Return

            If (lstErrors.SelectedItem.ToString().Substring(0, 1) = "-" Or lstErrors.SelectedItem.ToString() = " ") Then Return

            Dim iLine As Integer = CType(lstErrors.SelectedItem.ToString().Substring(0, lstErrors.SelectedItem.ToString().IndexOf(":")), Integer)

            If (IsNumeric(iLine) = False) Then Return

            Dim txtEditArea As RichTextBox = tcMain.SelectedTab.Controls("txtEditArea")

            Dim i As Integer = 0
            Dim n As Integer = 0
            Dim bFinished As Boolean = False

            For Each c As Char In txtEditArea.Text
                If (c = vbNewLine Or c = vbLf Or c = vbCr Or c = vbCrLf) Then
                    n += 1

                    If (n = iLine) Then
                        Exit For
                    End If
                End If

                i += 1
            Next

            txtEditArea.Select(i, 1)

            txtEditArea.ScrollToCaret()

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub lsmCheckSyntax_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lsmCheckSyntax.Click
        Try
            If (tcMain.TabPages.Count = 0) Then Return

            SyntaxCheck.CheckSyntax(tcMain.SelectedTab.Text, New ArrayList)

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub lstTodoList_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lstTodoList.MouseDoubleClick
        Try
            If (lstTodoList.Items.Count = 0) Then Return
            If (tcMain.TabPages.Count = 0) Then Return

            Dim iLine As Integer = CType(lstTodoList.SelectedItem.ToString().Substring(0, lstTodoList.SelectedItem.ToString().IndexOf(":")), Integer)

            If (IsNumeric(iLine) = False) Then Return

            Dim txtEditArea As RichTextBox = tcMain.SelectedTab.Controls("txtEditArea")

            Dim i As Integer = 0
            Dim n As Integer = 0
            Dim bFinished As Boolean = False

            For Each c As Char In txtEditArea.Text
                If (c = vbNewLine Or c = vbLf Or c = vbCr Or c = vbCrLf) Then
                    n += 1

                    If (n = iLine) Then
                        Exit For
                    End If
                End If

                i += 1
            Next

            txtEditArea.Select(i, 1)

            txtEditArea.ScrollToCaret()

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub tsmApplyHighlighting_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmApplyHighlighting.Click
        Try
            If (tcMain.TabPages.Count = 0) Then Return
            If (OpenProjects.ContainsKey(tcMain.SelectedTab.Text) = False) Then Return

            ProgramState = State.ApplyHighlight

            CType(OpenProjects(tcMain.SelectedTab.Text), Project).UpdateEvents(True)

            ProgramState = State.Idle

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Private Sub tsmAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmAbout.Click
        Try
            frmAbout.Show()

        Catch ex As Exception
            HandleException(ex)
        End Try
    End Sub

    Public Sub SelectLine(ByVal strProject As String, ByVal iLine As Integer)

    End Sub

    Private Sub tsmFNR_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsmFNR.Click
        frmFNR.Visible = True
    End Sub
End Class
